import {createStore} from 'vuex'
import router from "@/router";
import {$ajax, apiUrl} from "@/utils/ajax";
import {dayjs} from "element-plus";

export default createStore({
    state: {
        account: {}
    },
    getters: {},
    mutations: {
        logout(){
            window.localStorage.removeItem("account")
            this.state.account = {}
            router.replace({name: 'login'})
        }
    },
    actions: {
        getUser() {
            let account = window.localStorage.getItem("account");
            if (!account) {
                this.state.account = {}
                router.replace({name: 'login'})
                return {}
            }
            //判断是否已经过期
            account = JSON.parse(account)
            if (dayjs().diff(account.expireTime) > 0) {
                window.localStorage.removeItem("account")
                this.state.account = {}
                router.replace({name: 'login'})
                return {}
            }
            $ajax.post(`${apiUrl}authorization/checkAdminLogin`).then(({data: {result}}) => {
                this.state.account = result
            }).catch(() => {
                window.localStorage.removeItem("account")
                this.state.account = {}
                router.replace({name: 'login'})
            })
        }
    },
    modules: {}
})
